﻿using System.IO;
using System.Windows.Threading;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using machine_registration.Models;
using machine_registration.Services;
using Wpf.Ui.DependencyInjection;
using Wpf.Ui;
using machine_registration.Helpers;
using machine_registration.Infrastructure;
using Serilog;
using Serilog.Events;
using System.Text;
using Wpf.Ui.Demo.Mvvm.Services;   // 日志级别相关
namespace machine_registration
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        private static readonly IHost _host = Host.CreateDefaultBuilder()
            .ConfigureAppConfiguration(c =>
            {
                var basePath =
                    Path.GetDirectoryName(AppContext.BaseDirectory)
                    ?? throw new DirectoryNotFoundException(
                        "无法找到应用程序的基本目录"
                    );
                _ = c.SetBasePath(basePath);
               // c.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
           .UseSerilog((hostContext, loggerConfig) =>
           {
               loggerConfig
                  .ReadFrom.Configuration(hostContext.Configuration)
        .Enrich.FromLogContext()
        // 新增自定义上下文绑定 
        .Enrich.With(new CallerInfoEnricher())

                   // 输出配置
                   .WriteTo.File(
                       Path.Combine(Environment.CurrentDirectory, "logs", "log-.log"),
                       rollingInterval: RollingInterval.Day,
                        outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj} " +
                            "| Thread:{ThreadId} Line:{CallerLine} Method:{CallerMethod} " + // 修改此处 
                            "| {SourceContext}{NewLine}{Exception}",
                       encoding: Encoding.UTF8
                   )
                   .WriteTo.Debug(outputTemplate: "[{Level}] {Message} " +
                                                 "Thread:{ThreadId} Line:{LineNumber}");
           })
            .ConfigureServices(
                (context, services) =>
                {
                
                    _ = services.AddNavigationViewPageProvider();
               
                    services.AddTransient<IDataService, SqlDataService>();
                 
                 
                    _ = services.AddSingleton<IContentDialogService, ContentDialogService>();
                    // 添加日志系统
                    services.AddLogging(builder => builder.AddSerilog());
                    // App Host
                    _ = services.AddHostedService<ApplicationHostService>();

                    // Theme manipulation
                    _ = services.AddSingleton<IThemeService, ThemeService>();

                    // TaskBar manipulation
                    _ = services.AddSingleton<ITaskBarService, TaskBarService>();

                    // Service containing navigation, same as INavigationWindow... but without window
                    _ = services.AddSingleton<INavigationService, NavigationService>();

                  


                    // Main window with navigation
                    _ = services.AddSingleton<INavigationWindow, Views.MainWindow>();
                    _ = services.AddSingleton<ViewModels.MainWindowViewModel>();
            
                    // Views and ViewModels

                    _ = services.AddSingleton<Views.Pages.SettingsPage>();
                    _ = services.AddSingleton<ViewModels.SettingsViewModel>();

                    _ = services.AddTransient<Views.Pages.DataQueryPage>();
                    _ = services.AddTransient<ViewModels.DataQueryViewModel>();

                    _ = services.AddTransient<Views.Pages.BorrowPage>();
                    _ = services.AddTransient<ViewModels.BorrowPageViewModel>();

                    _ = services.AddTransient<Views.Pages.ReturnPage>();
                    _ = services.AddTransient<ViewModels.ReturnPageViewModel>();

                    _ = services.AddTransient<Views.Pages.LoanRecordPage>();
                    _ = services.AddTransient<ViewModels.LoanRecordPageViewModel>();

                    // Configuration
                    _ = services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
                    _ = services.AddDbContext<AppDbContext>( ServiceLifetime.Transient);


                    //注册消息推送数据源服务
                    _ = services.AddSingleton<IData_SourceService, TimeAlertManager>();
                    
                }
            )
            .Build();

        /// <summary>
        /// Gets services.
        /// </summary>
        public static IServiceProvider Services
        {
            get { return _host.Services; }
        }

        /// <summary>
        /// Occurs when the application is loading.
        /// </summary>
        private async void OnStartup(object sender, StartupEventArgs e)
        {
            await _host.StartAsync();
         
        
        }

        /// <summary>
        /// Occurs when the application is closing.
        /// </summary>
        private async void OnExit(object sender, ExitEventArgs e)
        {
            await _host.StopAsync();

            _host.Dispose();
        }

        /// <summary>
        /// Occurs when an exception is thrown by an application but not handled.
        /// </summary>
        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // 记录异常信息到日志文件或事件日志
            System.Diagnostics.Debug.WriteLine("未处理的异常: " + e.Exception.Message);
            // 或者使用日志框架记录异常
            // logger.LogError(e.Exception, "未处理的异常");

            // 显示友好的错误消息给用户
            MessageBox.Show("发生了一个错误: " + e.Exception.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);

            // 设置 e.Handled 为 true 表示异常已被处理
            e.Handled = true;

        }
  
    }

}
